<template>
  <div class="main-container container-fluid page-holder">
    <div class="page-title-holder">
      <h2 class="page-title">学习空间</h2>
    </div>
    <el-menu mode="horizontal" class="deep-color a-link-item" :default-active="active">
      <el-menu-item v-if="curUser.id" index="history">
        <router-link to="/spaces/history">最近访问</router-link>
      </el-menu-item>
      <el-menu-item index="all">
        <router-link to="/spaces/all">全部空间</router-link>
      </el-menu-item>
      <sign-in-tooltip>
        <el-menu-item index="collection">
          <router-link to="/spaces/collection">关注空间</router-link>
        </el-menu-item>
      </sign-in-tooltip>
      <sign-in-tooltip>
        <el-menu-item index="admin">
          <router-link to="/spaces/admin">管理空间</router-link>
        </el-menu-item>
      </sign-in-tooltip>
      <spaces-list-controls :active="active" />
    </el-menu>
    <spaces-list :spaces="spaces" :is-loading="loading" />
    <pagination :current-page="pagination.current" :page-count="pagination.count" />
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { formatSpacesList } from '@/components/spaces/format';
import SpacesListControls from '@/components/spaces/SpacesListControls';
import SpacesList from '@/components/spaces/SpacesList';

export default {
  name: 'SpacesIndex', // 空间列表
  components: {
    SpacesListControls,
    SpacesList,
  },
  data() {
    return {
      spaces: [],
      loading: false,
      pagination: {
        current: null,
        count: null,
      },
    };
  },
  computed: {
    ...mapState({
      curUser: 'currentUser',
    }),
    active() {
      return this.$route.path.split('/')[2] || (this.curUser.id ? 'history' : 'all');
    },
    // 加载空间列表所需参数
    loadSpacesParams() {
      const sortCombo = this.$route.query.sort || this.$C.sort.spacesSort[0].value;
      let sort = sortCombo.split('_')[0];
      if (sort === 'liked') sort = 'vote';
      return {
        type: this.active,
        page: this.$route.query.page || 1,
        sort,
        order: sortCombo.split('_')[1],
      };
    },
  },
  created() {
    this.loadSpaces();
  },
  methods: {
    // 加载空间列表
    loadSpaces() {
      this.loading = true;
      this.$api.spaces.index(this.loadSpacesParams)
        .then((res) => {
          this.spaces = formatSpacesList(res.data);
          this.pagination.current = res.kaminari.current_page;
          this.pagination.count = res.kaminari.total_pages;
        })
        .catch(() => {})
        .then(() => { this.loading = false; });
    },
  },
  watch: {
    loadSpacesParams() { this.loadSpaces(); },
  },
};
</script>

<style></style>
